//
//  Tabbar.swift
//  QQZone
//
//  Created by hjj on 2016/12/3.
//  Copyright © 2016年 hjjuny. All rights reserved.
//

import UIKit

protocol TabbarDelegate : class {
    func tabbar(tabbar : Tabbar, toIndex : Int, fromIndex : Int)
}

class Tabbar: UIView {
    
    // MARK: 属性
    weak var delegate : TabbarDelegate?
    var selectedItem : TabbarItem?
    
    // MARK: 构造函数
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupItem("tab_bar_feed_icon", "全部动态")
        setupItem("tab_bar_passive_feed_icon", "与我相关")
        setupItem("tab_bar_pic_wall_icon", "照片墙")
        setupItem("tab_bar_e_album_icon", "电子相框")
        setupItem("tab_bar_friend_icon", "好友")
        setupItem("tab_bar_e_more_icon", "更多")
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}

// MARK:- 添加子控件的函数
extension Tabbar {
    fileprivate func setupItem(_ iconName : String, _ title : String) {
        let item = TabbarItem()
        
        item.setTitle(title, for: .normal)
        item.setImage(UIImage(named: iconName), for: .normal)
        item.setBackgroundImage(UIImage(named: "tabbar_separate_selected_bg"), for: .selected)
        // 将当前子控件的个数赋值给item的tag
        item.tag = subviews.count
        
        item.addTarget(self, action: #selector(itemClick(_:)), for: .touchDown)
        
        addSubview(item)
    }
    
    @objc private func itemClick(_ item : TabbarItem) {
        // 通知代理
        delegate?.tabbar(tabbar: self, toIndex: item.tag, fromIndex: selectedItem?.tag ?? 0)
        
        // 交换三部曲
        selectedItem?.isSelected = false
        selectedItem = item
        selectedItem?.isSelected = true
    }
}

// MARK:- 对外提供的函数
extension Tabbar {
    func setupCurrentOritation(_ isLandscape : Bool) {
        // 0.获取个数
        let count = subviews.count
        
        // 1.调整自身的frame
        let w : CGFloat = superview!.frame.width
        let h : CGFloat = CGFloat(count) * kDockItemH
        let x : CGFloat = 0
        let y : CGFloat = 0
        frame = CGRect(x: x, y: y, width: w, height: h)
        
        // 2.调整子控件的frame
        for (index, item) in subviews.enumerated() {
            let itemW : CGFloat = w
            let itemH : CGFloat = kDockItemH
            let itemX : CGFloat = 0
            let itemY : CGFloat = itemH * CGFloat(index)
            item.frame = CGRect(x: itemX, y: itemY, width: itemW, height: itemH)
        }
    }
}
